#!/bin/bash

# ============================================================================
# TZYJ_IOS 项目专用打包脚本
# 支持：开发包(dev)、测试包(adhoc)、生产包(appstore)
# 
# ✅ 零污染设计：
# - 所有临时文件均在桌面输出目录中创建，不污染项目目录
# - 构建完成后自动清理所有临时文件，项目目录保持完全干净
# - 仅在必要时安装 CocoaPods 依赖，不强制更新现有依赖
# ============================================================================

set -e

# ============================================================================
# 项目配置 (已根据您的项目预设)
# ============================================================================

# 工作区路径
WORKSPACE_DIR="/Users/liyadong/Desktop/codeSpace/releaseDev/client_zyzq/TZYJ_IOS"

PROJECT_NAME="TzyjApp"
WORKSPACE_NAME="TZYJ_IOS.xcworkspace"
SCHEME_NAME="TzyjApp"
TARGET_NAME="TzyjTestApp"
BUNDLE_IDENTIFIER="com.thinkive.zhongyouzq"

# ============================================================================
# 需要您配置的证书信息
# ============================================================================

# 开发团队 ID (必填 - 请在 Xcode 项目设置中查看)
DEVELOPMENT_TEAM="TBUNG6LWN7"
CER_INFO_PATH="/Users/liyadong/Desktop/Dev_Day/cer_info"
# 证书文件路径和密码
DEV_P12_PATH="$CER_INFO_PATH/zyzq/dev.p12"
ADHOC_P12_PATH="$CER_INFO_PATH/zyzq/dis.p12"
APPSTORE_P12_PATH="$CER_INFO_PATH/zyzq/appstore.p12"

DEV_P12_PASSWORD="111111"
ADHOC_P12_PASSWORD="111111"  
APPSTORE_P12_PASSWORD="111111"

# 描述文件路径
DEV_PROFILE_PATH="$CER_INFO_PATH/zyzq/zyouzqhundsundis_wyw_Dev2025.mobileprovision"
ADHOC_PROFILE_PATH="$CER_INFO_PATH/zyzq/zyouzqhundsunadhoc_wyw_Adhoc2025.mobileprovision"
APPSTORE_PROFILE_PATH="$CER_INFO_PATH/zyzq/zyouzqhundsundis_wyw2025.mobileprovision"

# ============================================================================
# 颜色输出 (修复 echo 命令问题)
# ============================================================================

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 修复 echo 命令兼容性问题
print_info() { printf "${BLUE}[INFO]${NC} %s\n" "$1"; }
print_success() { printf "${GREEN}[SUCCESS]${NC} %s\n" "$1"; }
print_warning() { printf "${YELLOW}[WARNING]${NC} %s\n" "$1"; }
print_error() { printf "${RED}[ERROR]${NC} %s\n" "$1"; }

# ============================================================================
# 工具函数
# ============================================================================

# 获取指定的 Build 号或项目中的 Build 号
get_build_number() {
    local specified_build="$1"
    
    if [ -n "$specified_build" ]; then
        # 如果指定了 build 号，使用指定的
        print_info "使用指定的 Build 号: $specified_build" >&2
        echo "$specified_build"
    else
        # 如果没有指定，使用项目中的 build 号
        local project_build=$(get_project_build_number)
        print_info "使用项目中的 Build 号: $project_build" >&2
        echo "$project_build"
    fi
}

# 更新项目中的 Build 号
update_project_build_number() {
    local new_build="$1"
    local project_file="$WORKSPACE_DIR/TzyjApp/TzyjApp.xcodeproj/project.pbxproj"
    
    if [ ! -f "$project_file" ]; then
        print_warning "项目文件不存在，跳过 Build 号更新"
        return
    fi
    
    print_info "正在更新项目 Build 号为: $new_build"
    
    # 备份原文件
    cp "$project_file" "$project_file.backup"
    
    # 更新 CURRENT_PROJECT_VERSION (使用 macOS 兼容的 sed 命令)
    sed -i '' "s/CURRENT_PROJECT_VERSION = [0-9]*;/CURRENT_PROJECT_VERSION = $new_build;/g" "$project_file" 2>/dev/null || {
        # 如果 sed 失败，尝试使用 perl
        perl -pi -e "s/CURRENT_PROJECT_VERSION = [0-9]*;/CURRENT_PROJECT_VERSION = $new_build;/g" "$project_file"
    }
    
    # 验证更新是否成功
    local updated_build=$(grep -A 1 "CURRENT_PROJECT_VERSION" "$project_file" | grep -o '[0-9]\+' | head -n 1)
    if [ "$updated_build" = "$new_build" ]; then
        print_success "项目 Build 号已更新为: $new_build"
    else
        print_error "Build 号更新失败，期望: $new_build，实际: $updated_build"
        # 恢复备份文件
        mv "$project_file.backup" "$project_file"
        return 1
    fi
}

# 恢复项目中的 Build 号（构建完成后）
restore_project_build_number() {
    local project_file="$WORKSPACE_DIR/TzyjApp/TzyjApp.xcodeproj/project.pbxproj"
    local backup_file="$project_file.backup"
    
    if [ -f "$backup_file" ]; then
        print_info "正在恢复项目 Build 号..."
        mv "$backup_file" "$project_file"
        print_success "项目 Build 号已恢复"
    fi
}

# 获取项目版本信息
get_project_version_info() {
    local project_file="$WORKSPACE_DIR/TzyjApp/TzyjApp.xcodeproj/project.pbxproj"
    
    if [ ! -f "$project_file" ]; then
        echo "未知"
        return
    fi
    
    # 获取 MARKETING_VERSION (版本号)
    local marketing_version=$(grep -A 1 "MARKETING_VERSION" "$project_file" | grep -o '[0-9]\+\.[0-9]\+\.[0-9]\+' | head -n 1)
    if [ -z "$marketing_version" ]; then
        marketing_version="未知"
    fi
    
    echo "$marketing_version"
}

# 获取项目 Build 号
get_project_build_number() {
    local project_file="$WORKSPACE_DIR/TzyjApp/TzyjApp.xcodeproj/project.pbxproj"
    
    if [ ! -f "$project_file" ]; then
        echo "未知"
        return
    fi
    
    # 获取 CURRENT_PROJECT_VERSION (Build 号)
    local build_number=$(grep -A 1 "CURRENT_PROJECT_VERSION" "$project_file" | grep -o '[0-9]\+' | head -n 1)
    if [ -z "$build_number" ]; then
        build_number="未知"
    fi
    
    echo "$build_number"
}

# 获取证书信息
get_certificate_info() {
    local cert_path="$1"
    local cert_name="$2"
    
    if [ ! -f "$cert_path" ]; then
        echo "证书文件不存在: $cert_path"
        return
    fi
    
    # 获取证书文件基本信息
    local file_size=$(du -h "$cert_path" | cut -f1)
    local file_date=$(stat -f "%Sm" -t "%Y-%m-%d %H:%M:%S" "$cert_path")
    
    echo "证书名称: $cert_name"
    echo "证书文件: $(basename "$cert_path")"
    echo "文件大小: $file_size"
    echo "文件日期: $file_date"
    echo "证书类型: $(basename "$cert_path" | sed 's/\.[^.]*$//')"
    
    # 尝试从密钥链中获取证书信息（如果已安装）
    local cert_subject=$(security find-identity -v -p codesigning 2>/dev/null | grep "$(basename "$cert_path" | sed 's/\.[^.]*$//')" | head -n 1 | sed 's/.*"\(.*\)".*/\1/' || echo "")
    if [ -n "$cert_subject" ]; then
        echo "证书主题: $cert_subject"
    else
        echo "证书主题: 需要密码解密 (p12 文件)"
    fi
}

# 获取描述文件信息
get_provisioning_profile_info() {
    local profile_path="$1"
    local profile_name="$2"
    
    if [ ! -f "$profile_path" ]; then
        echo "描述文件不存在: $profile_path"
        return
    fi
    
    # 获取描述文件详细信息
    local profile_info=$(security cms -D -i "$profile_path" 2>/dev/null)
    if [ -z "$profile_info" ]; then
        echo "无法读取描述文件信息: $profile_path"
        return
    fi
    
    # 提取描述文件名称
    local name=$(echo "$profile_info" | plutil -extract Name xml1 - -o - | sed -n 's/.*<string>\(.*\)<\/string>.*/\1/p' | head -n 1)
    if [ -z "$name" ]; then
        name="未知"
    fi
    
    # 提取 UUID
    local uuid=$(echo "$profile_info" | plutil -extract UUID xml1 - -o - | sed -n 's/.*<string>\(.*\)<\/string>.*/\1/p' | head -n 1)
    if [ -z "$uuid" ]; then
        uuid="未知"
    fi
    
    # 提取 Team ID
    local team_id=$(echo "$profile_info" | plutil -extract TeamIdentifier xml1 - -o - | sed -n 's/.*<string>\(.*\)<\/string>.*/\1/p' | head -n 1)
    if [ -z "$team_id" ]; then
        team_id="未知"
    fi
    
    # 提取有效期
    local creation_date=$(echo "$profile_info" | plutil -extract CreationDate xml1 - -o - | sed -n 's/.*<string>\(.*\)<\/string>.*/\1/p' | head -n 1)
    local expiration_date=$(echo "$profile_info" | plutil -extract ExpirationDate xml1 - -o - | sed -n 's/.*<string>\(.*\)<\/string>.*/\1/p' | head -n 1)
    
    echo "描述文件名称: $name"
    echo "UUID: $uuid"
    echo "Team ID: $team_id"
    echo "创建时间: $creation_date"
    echo "过期时间: $expiration_date"
}

cleanup_certificates() {
    if [ -n "$TEMP_KEYCHAIN" ]; then
        # 恢复默认密钥链设置
        security default-keychain -d user -s login.keychain 2>/dev/null || true
        security delete-keychain "$TEMP_KEYCHAIN" 2>/dev/null || true
    fi
}

cleanup_temp_files() {
    # 清理可能存在的临时构建文件 (保证项目目录干净)
    if [ -n "$temp_build_dir" ] && [ -d "$temp_build_dir" ]; then
        rm -rf "$temp_build_dir"
    fi
    if [ -n "$temp_archives_dir" ] && [ -d "$temp_archives_dir" ]; then
        rm -rf "$temp_archives_dir" 
    fi
    if [ -n "$temp_logs_dir" ] && [ -d "$temp_logs_dir" ]; then
        rm -rf "$temp_logs_dir"
    fi
}

handle_error() {
    print_error "$1"
    cleanup_certificates
    cleanup_temp_files
    restore_project_build_number
    exit 1
}

install_certificate() {
    local p12_path="$1"
    local password="$2"
    local name="$3"
    
    [ ! -f "$p12_path" ] && handle_error "证书文件不存在: $p12_path"
    
    print_info "安装 $name 证书..."
    print_info "注意: 系统可能会要求输入密码，这是正常的"
    print_info "如果提示输入密码，请输入您的 macOS 用户密码"
    print_info "密码提示可能出现在以下情况："
    print_info "  1. 修改密钥链设置时"
    print_info "  2. 访问系统密钥链时" 
    print_info "  3. 代码签名过程中"
    print_info "这是 macOS 的安全机制，属于正常现象"
    
    TEMP_KEYCHAIN="ios_build_temp.keychain"
    security delete-keychain "$TEMP_KEYCHAIN" 2>/dev/null || true
    security create-keychain -p "111111" "$TEMP_KEYCHAIN"
    security set-keychain-settings -lut 21600 "$TEMP_KEYCHAIN"
    security unlock-keychain -p "111111" "$TEMP_KEYCHAIN"
    security import "$p12_path" -P "$password" -A -t cert -f pkcs12 -k "$TEMP_KEYCHAIN"
    
    # 设置密钥链搜索顺序，确保临时密钥链优先，并设置为默认密钥链
    # 使用 -T 参数避免密码提示，并添加更多错误处理
    security list-keychain -d user -s "$TEMP_KEYCHAIN" $(security list-keychain -d user | sed s/\"//g) 2>/dev/null || true
    security default-keychain -d user -s "$TEMP_KEYCHAIN" 2>/dev/null || true
    
    # 设置密钥链超时时间，避免频繁解锁
    security set-keychain-settings -t 3600 -u "$TEMP_KEYCHAIN" 2>/dev/null || true
    
    # 验证证书是否正确安装
    local cert_count=$(security find-identity -v -p codesigning "$TEMP_KEYCHAIN" 2>/dev/null | grep -c "iPhone Distribution" || echo "0")
    if [ "$cert_count" -eq 0 ]; then
        handle_error "证书安装失败，未找到有效的分发证书"
    fi
    
    print_success "$name 证书安装成功 (找到 $cert_count 个分发证书)"
}

install_provisioning_profile() {
    local profile_path="$1"
    local name="$2"
    
    [ ! -f "$profile_path" ] && handle_error "描述文件不存在: $profile_path"
    
    print_info "安装 $name 描述文件..."
    
    PROFILE_UUID=$(security cms -D -i "$profile_path" | plutil -extract UUID xml1 - -o - | sed -n 's/.*<string>\(.*\)<\/string>.*/\1/p')
    [ -z "$PROFILE_UUID" ] && handle_error "无法获取描述文件 UUID"
    
    mkdir -p "$HOME/Library/MobileDevice/Provisioning Profiles"
    cp "$profile_path" "$HOME/Library/MobileDevice/Provisioning Profiles/$PROFILE_UUID.mobileprovision"
    
    print_success "$name 描述文件安装成功"
}

build_and_export() {
    local build_type="$1"
    local config="$2"
    local export_method="$3"
    local specified_build="$4"
    
    print_info "开始构建 $build_type 包..."
    
    # 获取 Build 号
    local new_build_number=$(get_build_number "$specified_build")
    
    # 如果指定了 build 号，更新项目中的 Build 号
    if [ -n "$specified_build" ]; then
        if ! update_project_build_number "$new_build_number"; then
            return 1
        fi
    fi
    
    print_info "调试: 开始检查工作区文件..."
    
    # 检查工作区文件是否存在
    WORKSPACE_PATH="$WORKSPACE_DIR/$WORKSPACE_NAME"
    if [ ! -d "$WORKSPACE_PATH" ]; then
        handle_error "工作区文件不存在: $WORKSPACE_PATH"
    fi
    
    print_info "调试: 工作区文件检查完成"
    
    # 创建桌面输出目录 (时间戳+打包类型)
    local timestamp=$(date +%Y%m%d_%H%M%S)
    local desktop_output_dir="$HOME/Desktop/${timestamp}_${build_type}"
    mkdir -p "$desktop_output_dir"
    
    # 创建临时构建目录 (不在项目内)
    local temp_build_dir="$desktop_output_dir/temp_build"
    local temp_archives_dir="$desktop_output_dir/temp_archives"
    local temp_logs_dir="$desktop_output_dir/temp_logs"
    mkdir -p "$temp_build_dir" "$temp_archives_dir" "$temp_logs_dir"
    
    # 归档路径 (使用临时目录)
    local archive_path="$temp_archives_dir/${PROJECT_NAME}_${build_type}_${timestamp}.xcarchive"
    
    # 构建归档
    print_info "正在归档项目..."
    print_info "这可能需要几分钟时间，请耐心等待..."
    print_info "调试: 准备执行 xcodebuild 命令"
    
    # 实时显示构建进度
    xcodebuild archive \
        -workspace "$WORKSPACE_PATH" \
        -scheme "$SCHEME_NAME" \
        -configuration "$config" \
        -archivePath "$archive_path" \
        -destination "generic/platform=iOS" \
        DEVELOPMENT_TEAM="$DEVELOPMENT_TEAM" \
        CODE_SIGN_STYLE="Manual" \
        CODE_SIGN_IDENTITY="iPhone Distribution: China Post Securities Co.Ltd. (TBUNG6LWN7)" \
        OTHER_CODE_SIGN_FLAGS="--keychain $TEMP_KEYCHAIN" \
        DEBUG_INFORMATION_FORMAT="dwarf-with-dsym" \
        ENABLE_BITCODE="NO" \
        2>&1 | tee "$temp_logs_dir/build_${build_type}.log"
    
    local build_result=${PIPESTATUS[0]}
    if [ $build_result -ne 0 ]; then
        print_error "归档失败 (退出码: $build_result)"
        print_error "查看构建日志: $temp_logs_dir/build_${build_type}.log"
        print_error "常见原因: 1) Scheme配置错误 2) 代码编译错误 3) 证书配置问题"
        printf "最后几行构建日志:\n"
        tail -10 "$temp_logs_dir/build_${build_type}.log"
        return 1
    fi
    
    # 检查归档文件是否存在且有效
    if [ ! -d "$archive_path" ]; then
        print_error "归档文件不存在: $archive_path"
        return 1
    fi
    
    # 检查归档文件中是否包含应用
    if [ ! -d "$archive_path/Products/Applications" ] || [ -z "$(ls -A "$archive_path/Products/Applications" 2>/dev/null)" ]; then
        print_error "归档文件中没有应用程序，构建可能失败"
        print_error "归档内容:"
        ls -la "$archive_path/Products/" 2>/dev/null || printf "Products目录不存在\n"
        return 1
    fi
    
    print_success "归档成功: $archive_path"
    
    # 创建导出配置 (使用临时目录)
    local export_plist="$temp_build_dir/ExportOptions_${build_type}.plist"
    cat > "$export_plist" << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>method</key>
    <string>$export_method</string>
    <key>teamID</key>
    <string>$DEVELOPMENT_TEAM</string>
    <key>uploadBitcode</key>
    <false/>
    <key>uploadSymbols</key>
    <true/>
    <key>compileBitcode</key>
    <false/>
    <key>provisioningProfiles</key>
    <dict>
        <key>$BUNDLE_IDENTIFIER</key>
        <string>$PROFILE_UUID</string>
    </dict>
</dict>
</plist>
EOF
    
    # 导出 IPA 到桌面目录
    local export_path="$desktop_output_dir/temp_export"
    print_info "正在导出 IPA 到桌面..."
    
    xcodebuild -exportArchive \
        -archivePath "$archive_path" \
        -exportPath "$export_path" \
        -exportOptionsPlist "$export_plist" \
        OTHER_CODE_SIGN_FLAGS="--keychain $TEMP_KEYCHAIN" \
        2>&1 | tee "$temp_logs_dir/export_${build_type}.log"
    
    local export_result=${PIPESTATUS[0]}
    if [ $export_result -ne 0 ]; then
        print_error "导出失败 (退出码: $export_result)"
        print_error "查看导出日志: $temp_logs_dir/export_${build_type}.log"
        printf "最后几行导出日志:\n"
        tail -15 "$temp_logs_dir/export_${build_type}.log"
        return 1
    fi
    
    # 移动 IPA 到桌面目录并重命名
    local ipa_file=$(find "$export_path" -name "*.ipa" | head -n 1)
    if [ -n "$ipa_file" ]; then
        local final_name="${PROJECT_NAME}_${build_type}_${timestamp}.ipa"
        mv "$ipa_file" "$desktop_output_dir/$final_name"
        
        # 保留 XCArchive 文件
        local archive_name="${PROJECT_NAME}_${build_type}_${timestamp}.xcarchive"
        if [ -d "$archive_path" ]; then
            print_info "正在复制 XCArchive 文件..."
            cp -R "$archive_path" "$desktop_output_dir/$archive_name"
            print_success "XCArchive 文件已保存: $archive_name"
        fi
        
        # 保留导出配置文件
        if [ -f "$export_plist" ]; then
            local plist_name="ExportOptions_${build_type}_${timestamp}.plist"
            cp "$export_plist" "$desktop_output_dir/$plist_name"
            print_info "导出配置文件已保存: $plist_name"
        fi
        
        # 提取并保存 DYSM 文件
        print_info "正在提取 DYSM 文件..."
        local dsym_source="$archive_path/dSYMs"
        if [ -d "$dsym_source" ]; then
            # 查找主应用的 dSYM 文件
            local app_dsym=$(find "$dsym_source" -name "*.dSYM" | head -n 1)
            if [ -n "$app_dsym" ]; then
                local dsym_name="${PROJECT_NAME}_${build_type}_${timestamp}.dSYM"
                cp -R "$app_dsym" "$desktop_output_dir/$dsym_name"
                print_success "DYSM 文件已保存: $dsym_name"
                
                # 显示 DYSM 文件大小
                local dsym_size=$(du -h "$desktop_output_dir/$dsym_name" | cut -f1)
                print_info "DYSM 文件大小: $dsym_size"
            else
                print_warning "未找到 DYSM 文件"
            fi
            
            # 查找所有 dSYM 文件（包括第三方库）
            local all_dsyms=$(find "$dsym_source" -name "*.dSYM")
            if [ -n "$all_dsyms" ]; then
                local dsyms_dir="$desktop_output_dir/dSYMs_${build_type}_${timestamp}"
                mkdir -p "$dsyms_dir"
                cp -R "$dsym_source"/* "$dsyms_dir/"
                print_success "所有 DYSM 文件已保存到: dSYMs_${build_type}_${timestamp}"
            fi
        else
            print_warning "归档文件中没有 dSYMs 目录"
        fi
        
        # 清理临时导出目录
        rm -rf "$export_path"
        
        # 日志文件保留在临时目录中，不导出到最终目录
        
        # 恢复项目中的 Build 号
        restore_project_build_number
        
        # 获取版本信息
        local project_version=$(get_project_version_info)
        local project_build=$(get_project_build_number)
        
        # 获取证书和描述文件信息
        local cert_info=""
        local profile_info=""
        
        case "$build_type" in
            "Development")
                cert_info=$(get_certificate_info "$DEV_P12_PATH" "开发证书")
                profile_info=$(get_provisioning_profile_info "$DEV_PROFILE_PATH" "开发描述文件")
                ;;
            "AdHoc")
                cert_info=$(get_certificate_info "$ADHOC_P12_PATH" "Ad Hoc 证书")
                profile_info=$(get_provisioning_profile_info "$ADHOC_PROFILE_PATH" "Ad Hoc 描述文件")
                ;;
            "AppStore")
                cert_info=$(get_certificate_info "$APPSTORE_P12_PATH" "App Store 证书")
                profile_info=$(get_provisioning_profile_info "$APPSTORE_PROFILE_PATH" "App Store 描述文件")
                ;;
        esac
        
        # 创建构建信息文件
        local build_info_file="$desktop_output_dir/build_info_${build_type}_${timestamp}.txt"
        cat > "$build_info_file" << EOF
构建信息
==========

项目信息:
- 项目名称: $PROJECT_NAME
- Target: $TARGET_NAME
- Scheme: $SCHEME_NAME
- Bundle ID: $BUNDLE_IDENTIFIER
- 开发团队: $DEVELOPMENT_TEAM

版本信息:
- 构建类型: $build_type
- 版本号: $project_version
- Build 号: $new_build_number
- 构建时间: $(date)

证书信息:
$cert_info

描述文件信息:
$profile_info

文件列表:
- ${final_name} (IPA 文件)
- ${archive_name} (XCArchive 文件)
- ${PROJECT_NAME}_${build_type}_${timestamp}.dSYM (主应用调试符号)
- dSYMs_${build_type}_${timestamp}/ (所有调试符号文件)
- ExportOptions_${build_type}_${timestamp}.plist (导出配置)

构建环境:
- Xcode 版本: $(xcodebuild -version | head -n 1)
- macOS 版本: $(sw_vers -productVersion)
- 构建路径: $WORKSPACE_DIR
EOF
        print_info "构建信息文件已保存: build_info_${build_type}_${timestamp}.txt"
        
        # 清理所有临时目录
        rm -rf "$temp_build_dir" "$temp_logs_dir" "$temp_archives_dir"
        
        print_success "$build_type 包构建完成!"
        print_success "📁 输出目录: $desktop_output_dir"
        print_success "📱 版本号: $project_version"
        print_success "🔢 Build 号: $new_build_number"
        print_success "📦 IPA 文件: $final_name"
        print_success "📦 XCArchive 文件: $archive_name"
        print_success "🐛 DYSM 文件: ${PROJECT_NAME}_${build_type}_${timestamp}.dSYM"
        print_success "🐛 所有调试符号: dSYMs_${build_type}_${timestamp}/"
        print_success "📋 导出配置: ExportOptions_${build_type}_${timestamp}.plist"
        print_success "📋 构建信息: build_info_${build_type}_${timestamp}.txt"
        
        # 显示文件大小
        local ipa_size=$(du -h "$desktop_output_dir/$final_name" | cut -f1)
        local archive_size=$(du -h "$desktop_output_dir/$archive_name" | cut -f1)
        print_info "IPA 文件大小: $ipa_size"
        print_info "XCArchive 文件大小: $archive_size"
        
        # 在Finder中显示文件夹
        open "$desktop_output_dir"
    else
        handle_error "未找到导出的 IPA 文件"
    fi
}

# ============================================================================
# 三种打包类型
# ============================================================================

build_dev() {
    local build_number="$1"
    print_info "========== 构建开发包 =========="
    install_certificate "$DEV_P12_PATH" "$DEV_P12_PASSWORD" "开发"
    install_provisioning_profile "$DEV_PROFILE_PATH" "开发"
    build_and_export "Development" "Debug" "development" "$build_number"
    cleanup_certificates
}

build_adhoc() {
    local build_number="$1"
    print_info "========== 构建测试包 =========="
    install_certificate "$ADHOC_P12_PATH" "$ADHOC_P12_PASSWORD" "Ad Hoc"
    install_provisioning_profile "$ADHOC_PROFILE_PATH" "Ad Hoc"
    print_info "准备调用 build_and_export 函数..."
    build_and_export "AdHoc" "Release" "release-testing" "$build_number"
    print_info "build_and_export 函数执行完成"
    cleanup_certificates
}

build_appstore() {
    local build_number="$1"
    print_info "========== 构建生产包 =========="
    install_certificate "$APPSTORE_P12_PATH" "$APPSTORE_P12_PASSWORD" "App Store"
    install_provisioning_profile "$APPSTORE_PROFILE_PATH" "App Store"
    build_and_export "AppStore" "Release" "app-store" "$build_number"
    cleanup_certificates
}

# ============================================================================
# 使用说明和主函数
# ============================================================================

show_help() {
    printf "TZYJ_IOS 项目打包脚本\n"
    printf "\n"
    printf "用法: %s [类型] [build号]\n" "$0"
    printf "\n"
    printf "打包类型:\n"
    printf "  dev        构建开发包 (Debug 版本，用于开发调试)\n"
    printf "  adhoc      构建测试包 (Release 版本，用于内部测试)\n"
    printf "  appstore   构建生产包 (Release 版本，用于 App Store)\n"
    printf "  build      查看项目中的 Build 号\n"
    printf "\n"
    printf "Build 号参数 (可选):\n"
    printf "  如果指定 build 号，将使用指定的 build 号\n"
    printf "  如果不指定，将使用项目中的 build 号\n"
    printf "\n"
    printf "示例:\n"
    printf "  %s dev              # 构建开发包，使用项目中的 build 号\n" "$0"
    printf "  %s adhoc            # 构建测试包，使用项目中的 build 号\n" "$0"
    printf "  %s appstore         # 构建生产包，使用项目中的 build 号\n" "$0"
    printf "  %s adhoc 100        # 构建测试包，使用 build 号 100\n" "$0"
    printf "  %s dev 50           # 构建开发包，使用 build 号 50\n" "$0"
    printf "  %s build            # 查看项目中的 Build 号\n" "$0"
    printf "\n"
    printf "Build 号管理:\n"
    printf "  - 不指定 build 号时，使用项目中的 build 号\n"
    printf "  - 指定 build 号时，会临时更新项目文件\n"
    printf "  - 构建完成后会恢复项目文件到原始状态\n"
    printf "\n"
}

main() {
    # 检查参数
    if [ $# -eq 0 ]; then
        show_help
        exit 0
    fi
    
    # 检查配置
    if [ -z "$DEVELOPMENT_TEAM" ]; then
        print_error "请先配置 DEVELOPMENT_TEAM (开发团队 ID)"
        exit 1
    fi
    
    # 检查 CocoaPods (仅在必要时更新，不强制修改项目结构)
    if [ -f "$WORKSPACE_DIR/Podfile" ] && command -v pod &> /dev/null; then
        if [ ! -f "$WORKSPACE_DIR/Podfile.lock" ] || [ ! -d "$WORKSPACE_DIR/Pods" ]; then
            print_info "首次安装 CocoaPods 依赖..."
            cd "$WORKSPACE_DIR" && pod install --repo-update
        else
            print_info "CocoaPods 依赖已存在，跳过更新 (保持项目文件不变)"
        fi
    fi
    
    # 获取 build 号参数
    local build_number="$2"
    
    # 执行对应的打包类型
    case "$1" in
        dev)
            build_dev "$build_number"
            ;;
        adhoc)
            build_adhoc "$build_number"
            ;;
        appstore)
            build_appstore "$build_number"
            ;;
        build)
            # 显示项目版本信息
            local project_version=$(get_project_version_info)
            local project_build=$(get_project_build_number)
            print_info "项目版本号: $project_version"
            print_info "项目 Build 号: $project_build"
            ;;
        *)
            print_error "未知的打包类型: $1"
            show_help
            exit 1
            ;;
    esac
    
    print_success "打包完成！IPA 文件已保存到桌面对应的时间戳文件夹中"
}

# 确保退出时清理所有临时文件
trap 'cleanup_certificates; cleanup_temp_files' EXIT

# 运行主函数
main "$@" 